<template>
  <div class="goods-image">
    <div
      class="large"
      v-if="!isOutside"
      :style="{
        backgroundImage: `url(${images[currIndex]})`,
        backgroundPositionX: -2 * layer.left + 'px',
        backgroundPositionY: -2 * layer.top + 'px'
      }"
    ></div>
    <div class="middle" ref="middle">
      <!-- 遮罩层 -->
      <div
        class="layer"
        :style="{ top: layer.top + 'px', left: layer.left + 'px' }"
        v-if="!isOutside"
      ></div>
      <img :src="images[currIndex]" alt="" />
    </div>
    <ul class="small">
      <li
        v-for="(i, index) in images"
        :key="index"
        :class="{ active: currIndex === index }"
        @mouseenter="currIndex = index"
      >
        <img :src="i" alt="" />
      </li>
    </ul>
  </div>
</template>
<script>
import { ref, watch } from 'vue'
import { useMouseInElement } from '@vueuse/core'
export default {
  name: 'GoodsImage',
  props: {
    images: {
      type: Array,
      default: () => []
    }
  },
  setup () {
    const currIndex = ref(0)
    const middle = ref(null)
    const { isOutside, elementX, elementY } = useMouseInElement(middle)
    const layer = ref({
      top: 0,
      left: 0
    })
    watch(
      [elementX, elementY],
      () => {
        layer.value.left = elementX.value - 100
        layer.value.top = elementY.value - 100
        // 左边
        if (elementX.value < 100) {
          layer.value.left = 0
        }
        // 右边
        if (elementX.value > 300) {
          layer.value.left = 200
        }
        // 上边
        if (elementY.value < 100) {
          layer.value.top = 0
        }
        // 下边
        if (elementY.value > 300) {
          layer.value.top = 200
        }
      },
      {
        immediate: true
      }
    )
    return { currIndex, middle, isOutside, layer }
  }
}
</script>
<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  z-index: 500;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    position: relative;
    cursor: move;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, 0.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
